package com.chushouya.product.service.api.impl;

import com.chushouya.product.dao.entity.*;
import com.chushouya.product.dao.repository.*;
import com.chushouya.product.dto.admin.productsku.ProductSkuQuery;
import com.chushouya.product.dto.api.evaluate.*;
import com.chushouya.product.dto.api.evaluatedata.*;
import com.general.framework.core.lang.Check;
import com.general.framework.core.lang.Lists;
import com.general.framework.core.lang.Strings;
import com.chushouya.product.constants.EvaluateTypeEnum;
//=====product.dto.api.evaluate.*;
import com.chushouya.product.dto.api.evaluate.*;
import com.chushouya.product.service.api.EvaluateDataApiService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

@Slf4j
@Service
public class EvaluateDataApiServiceImpl implements EvaluateDataApiService {

    private static final TypeReference<List<Map<String, Object>>> ATTR_VALUES_TYPE_REF = 
            new TypeReference<List<Map<String, Object>>>() {};
    
    private static final String VALUE_ID_KEY = "valueId";
    private static final String VALUE_CONTENT_KEY = "valueContent";

    @Resource
    private ProductRepository productRepository;

    @Resource
    private ProductSkuRepository productSkuRepository;
    
    @Resource
    private ProductAttrRepository productAttrRepository;
    
    @Resource
    private SkuEvaluateItemRepository skuEvaluateItemRepository;
    
    @Resource
    private SkuEvaluateItemValueRepository skuEvaluateItemValueRepository;
    
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public EvaluateDataProductApiDTO evaluateProduct(EvaluateDataProductRequestApiDTO request) {
        Check.notNull(request, "请求参数不能为空");
        Check.notNull(request.getProductId(), "商品ID不能为空");
        
        Long productId = request.getProductId();
        log.debug("开始获取商品估价信息, productId: {}", productId);
        
        // 1. 获取商品基本信息
        ProductEntity product = getProduct(productId);
        
        // 2. 获取商品属性信息
        List<ProductAttrEntity> productAttrs = productAttrRepository.selectListByProductId(productId);
        log.debug("获取到商品属性数量: {}", productAttrs.size());
        
        // 3. 构建返回结果
        EvaluateDataProductApiDTO result = buildEvaluateProductApiDTO(product);
        
        // 4. 构建评估项目列表
        List<EvaluateListApiDTO> evaluateList = buildSkuEvaluateList(productAttrs);
        result.setEvaluateList(evaluateList);
        
        log.debug("商品估价信息构建完成, 评估项目数量: {}", evaluateList.size());
        return result;
    }

    @Override
    public EvaluateDataItemApiDTO evaluateItem(EvaluateDataItemRequestApiDTO request) {
        Check.notNull(request, "请求参数不能为空");
        Check.notNull(request.getProductId(), "商品ID不能为空");

        final Long productId = request.getProductId();
        final String skuCode = processSkuCode(request.getSkuCode());
        log.debug("开始获取SKU估价项目信息, productId: {}", productId);

        // 0. 处理特殊情况
        EvaluateDataItemApiDTO result = new EvaluateDataItemApiDTO();
        result.setProductId(productId);
        
        // b. SKU为空的情况
        if (Strings.isEmpty(skuCode)) {
            log.debug("SKU为空，返回空的评估列表，skuId=0");
            result.setSkuId(0L);
            result.setEvaluateList(Collections.emptyList());
            return result;
        }
        
        // 校验skuCode是否存在
        ProductSkuEntity productSkuEntity = null;
        try {
            productSkuEntity = this.getProductSku(productId, skuCode);
        } catch (Exception e) {
            log.warn("SKU不存在: productId={}, skuCode={}", productId, skuCode);
            result.setSkuId(0L);
            result.setEvaluateList(Collections.emptyList());
            return result;
        }
        
        // a. SKU名称包含"全新包装未拆封"的情况
        if (containsNewPackageKeyword(productSkuEntity.getSkuName())) {
            log.debug("SKU名称包含全新包装未拆封，返回空的评估列表，skuId={}, skuName={}", 
                    productSkuEntity.getSkuId(), productSkuEntity.getSkuName());
            result.setSkuId(productSkuEntity.getSkuId());
            result.setEvaluateList(Collections.emptyList());
            return result;
        }
        
        // 1. 查询该商品下的所有SKU估价项目
        List<SkuEvaluateItemEntity> skuItems = skuEvaluateItemRepository.selectListByProductId(productId);
        log.debug("获取到SKU估价项目数量: {}", skuItems.size());
        
        // 2. 构建评估项目列表
        List<EvaluateListApiDTO> evaluateList = buildEvaluateList(skuItems);
        
        // 3. 构建返回结果
        result.setSkuId(productSkuEntity.getSkuId());
        result.setEvaluateList(evaluateList);
        
        log.debug("SKU估价项目信息构建完成, 评估项目数量: {}", evaluateList.size());
        return result;
    }

    @Override
    public EvaluateDataResultApiDTO evaluateResult(EvaluateDataRequestApiDTO request) {
        return null;
    }

    /**
     * 获取商品信息
     */
    private ProductEntity getProduct(Long productId) {
        ProductEntity productEntity = productRepository.selectByPrimaryKey(productId);
        Check.notNull(productEntity, "商品不存在");
        return productEntity;
    }
    
    /**
     * 构建商品估价基本信息
     */
    private EvaluateDataProductApiDTO buildEvaluateProductApiDTO(ProductEntity product) {
        EvaluateDataProductApiDTO result = new EvaluateDataProductApiDTO();
        result.setProductId(product.getProductId());
        result.setProductName(product.getProductName());
        result.setProductImage(product.getProductImage());
        result.setMaxPrice(product.getMaxPrice());
        return result;
    }
    
    /**
     * 构建SKU评估项目列表
     */
    private List<EvaluateListApiDTO> buildSkuEvaluateList(List<ProductAttrEntity> productAttrs) {
        if (Lists.isEmpty(productAttrs)) {
            return Collections.emptyList();
        }
        
        return productAttrs.stream()
                .map(this::buildEvaluateListItem)
                .collect(Collectors.toList());
    }
    
    /**
     * 构建单个评估项目
     */
    private EvaluateListApiDTO buildEvaluateListItem(ProductAttrEntity attr) {
        EvaluateListApiDTO evaluateItem = new EvaluateListApiDTO();
        evaluateItem.setAttrId(attr.getAttrId());
        evaluateItem.setAttrName(attr.getAttrName());
        evaluateItem.setIsMultiSelect(false); // 默认单选
        evaluateItem.setEvaluateType(EvaluateTypeEnum.SKU.value()); // 默认类型
        
        // 解析JSON格式的attrValues，提取valueId和valueContent
        List<EvaluateValueApiDTO> attrValues = parseAttrValues(attr.getAttrValues());
        evaluateItem.setAttrValues(attrValues);
        
        return evaluateItem;
    }
    
    /**
     * 解析JSON格式的属性值
     * 示例: [{"valueId":"100001","valueContent":"已拆封可正常开机"}]
     * 示例: [{"valueId":"100022","valueContent":"不足一个月"},{"valueId":"100021","valueContent":"一个月以上"}]
     */
    private List<EvaluateValueApiDTO> parseAttrValues(String attrValuesJson) {
        if (Strings.isEmpty(attrValuesJson)) {
            return Collections.emptyList();
        }
        
        try {
            List<Map<String, Object>> valueList = objectMapper.readValue(attrValuesJson, ATTR_VALUES_TYPE_REF);
            
            return valueList.stream()
                    .map(this::buildEvaluateValueApiDTO)
                    .collect(Collectors.toList());
                    
        } catch (JsonProcessingException e) {
            log.warn("解析商品属性值JSON失败, attrValues: {}, error: {}", attrValuesJson, e.getMessage());
            return Collections.emptyList();
        }
    }
    
    /**
     * 构建评估值DTO
     */
    private EvaluateValueApiDTO buildEvaluateValueApiDTO(Map<String, Object> valueMap) {
        EvaluateValueApiDTO valueDTO = new EvaluateValueApiDTO();
        
        Object valueIdObj = valueMap.get(VALUE_ID_KEY);
        Object valueContentObj = valueMap.get(VALUE_CONTENT_KEY);
        
        if (valueIdObj != null) {
            try {
                valueDTO.setValueId(Long.valueOf(valueIdObj.toString()));
            } catch (NumberFormatException e) {
                log.warn("valueId格式错误: {}", valueIdObj);
            }
        }
        
        if (valueContentObj != null) {
            valueDTO.setValueContent(valueContentObj.toString());
        }
        
        return valueDTO;
    }
    
    /**
     * 构建评估项目列表
     */
    private List<EvaluateListApiDTO> buildEvaluateList(List<SkuEvaluateItemEntity> skuItems) {
        if (Lists.isEmpty(skuItems)) {
            return Collections.emptyList();
        }
        
        return skuItems.stream()
                .map(this::buildSkuEvaluateListItem)
                .collect(Collectors.toList());
    }
    
    /**
     * 构建单个SKU评估项目
     */
    private EvaluateListApiDTO buildSkuEvaluateListItem(SkuEvaluateItemEntity skuItem) {
        EvaluateListApiDTO evaluateItem = new EvaluateListApiDTO();
        evaluateItem.setAttrId(skuItem.getItemId());
        evaluateItem.setAttrName(skuItem.getItemName());
        evaluateItem.setIsMultiSelect(determineMultiSelect(skuItem.getSelectType()));
        evaluateItem.setEvaluateType(EvaluateTypeEnum.ITEM.value());
        
        // 查询该SKU估价项目下的所有选项值
        List<SkuEvaluateItemValueEntity> skuValues = skuEvaluateItemValueRepository.selectListBySkuItemId(skuItem.getSkuItemId());
        List<EvaluateValueApiDTO> attrValues = buildSkuEvaluateValues(skuValues);
        evaluateItem.setAttrValues(attrValues);
        
        return evaluateItem;
    }
    
    /**
     * 构建SKU评估值列表
     */
    private List<EvaluateValueApiDTO> buildSkuEvaluateValues(List<SkuEvaluateItemValueEntity> skuValues) {
        if (Lists.isEmpty(skuValues)) {
            return Collections.emptyList();
        }
        
        return skuValues.stream()
                .map(this::buildSkuEvaluateValueApiDTO)
                .collect(Collectors.toList());
    }
    
    /**
     * 构建SKU评估值DTO
     */
    private EvaluateValueApiDTO buildSkuEvaluateValueApiDTO(SkuEvaluateItemValueEntity skuValue) {
        EvaluateValueApiDTO valueDTO = new EvaluateValueApiDTO();
        valueDTO.setValueId(skuValue.getSkuItemValueId());
        valueDTO.setValueContent(skuValue.getValueName());
        return valueDTO;
    }
    
    /**
     * 根据选择类型判断是否多选
     */
    private Boolean determineMultiSelect(Integer selectType) {
        // 根据业务规则判断，这里假设1为单选，2为多选
        return selectType != null && selectType == 2;
    }


    /**
     * 查询sku信息
     */
    private ProductSkuEntity getProductSku(Long productId, String skuCode) {
        ProductSkuQuery query = new ProductSkuQuery();
        query.setProductId(productId);
        query.setSkuCode(skuCode);
        ProductSkuEntity skuEntity = productSkuRepository.selectOne(query);
        Check.notNull(skuEntity, "商品SKU不存在");
        return skuEntity;
    }
    
    /**
     * 检查SKU名称是否包含"全新包装未拆封"关键词
     */
    private boolean containsNewPackageKeyword(String skuName) {
        if (Strings.isEmpty(skuName)) {
            return false;
        }
        
        // 检查常见的"全新包装未拆封"相关关键词
        String[] keywords = {
            "全新包装未拆封", "全新未拆封", "全新包装", "未拆封", 
            "全新", "新品", "原装未拆", "原包装"
        };
        
        String lowerSkuName = skuName.toLowerCase();
        for (String keyword : keywords) {
            if (lowerSkuName.contains(keyword.toLowerCase())) {
                return true;
            }
        }
        
        return false;
    }

    /**
     * 处理skuCode  使100001:100001,100002:100069,100003:100017,100004:100031 使其必须按照第一个数字升序 100001  100002 100003  100004 升序
     */
    private String processSkuCode(String skuCode) {
        if (skuCode == null || skuCode.trim().isEmpty()) {
            return skuCode;
        }
        
        try {
            // 按逗号分割各个键值对
            String[] pairs = skuCode.split(",");
            
            // 使用TreeMap自动按key排序（key为Long类型确保数字排序正确）
            Map<Long, String> sortedMap = new TreeMap<>();
            
            for (String pair : pairs) {
                if (pair.contains(":")) {
                    String[] keyValue = pair.split(":", 2);
                    if (keyValue.length == 2) {
                        try {
                            Long key = Long.parseLong(keyValue[0].trim());
                            String value = keyValue[1].trim();
                            sortedMap.put(key, value);
                        } catch (NumberFormatException e) {
                            // 如果解析失败，保持原样
                            continue;
                        }
                    }
                }
            }
            
            // 重新组装排序后的字符串
            return sortedMap.entrySet().stream()
                    .map(entry -> entry.getKey() + ":" + entry.getValue())
                    .collect(Collectors.joining(","));
                    
        } catch (Exception e) {
            // 如果处理过程中出现异常，返回原始字符串
            return skuCode;
        }
    }
}
